package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.ApplyProNoticeActivity;
import com.linkage.jz.bankruptcy.activity.Project.CreateProjectDetailThreeActivity;
import com.linkage.jz.bankruptcy.activity.Project.EditProjectDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProDetailActivity;
//import com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQOneProjectActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.EditZQUserBaseInfoActivity;
import com.linkage.jz.bankruptcy.adapter.MyProListViewAdapter;
import com.linkage.jz.bankruptcy.adapter.ProjectBaseAdapter;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.bean.NoticeInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.LoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicLoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicLongNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.RecyclerViewNoBugLinearLayoutManager;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.register.RegisterActivity;
import com.linkage.seapeak.base.BaseFragment;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/30.
 */

public class MyProFragment extends BaseFragment implements AYSwipeRecyclerView.OnRefreshLoadListener {

    //显示信息
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();
    private ProjectBaseAdapter mAdapter;
    private ArrayList<MyProInfo> mData;
    private View ll_nodata;

    private AYSwipeRecyclerView mDataRv;
    private ShapeLoadingDialog shapeLoadingDialog;
    private PublicNoticeDialog noticeDialog;
    private PublicLongNoticeDialog noticelxDialog;

    int page = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_mypro, container, false);
        mDataRv = (AYSwipeRecyclerView) view.findViewById(R.id.rv_recyclerview_data);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initRecyclerView();
        shapeLoadingDialog = new ShapeLoadingDialog(getActivity());
    }

    @Override
    public void onResume() {
        super.onResume();
        loadFirst();
    }

    private void initRecyclerView() {
        ll_nodata = LayoutInflater.from(getActivity()).inflate(R.layout.empty_pro_mypro, null);
        mData = new ArrayList<MyProInfo>();
        mAdapter = new ProjectBaseAdapter(getActivity(), mData, ProjectBaseAdapter.PROJECT_MINE);
        mDataRv.setEmptyView(ll_nodata);
        mDataRv.setShowEmpty(true);
//        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
//                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
//                }
//            }
//        });
        mDataRv.setOnRefreshLoadLister(this);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                if(position >mData.size() || position == mData.size())
                {

                    return;
                }
                MyProInfo model = mData.get(position);

                BankruptcyApp.mphone = model.getContactPhone();
                BankruptcyApp.mUserid =model.getSendSysUserId();
                BankruptcyApp.mUsername = model.getContacts();

                if (v.getId() == R.id.bt_item_bt1) {
                    if (model.getProjectColumnList().getFillingIn()) {
                        ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                        info.setBankruptcyProjectId(model.getId());
                        info.setId(model.getCreditorId());
                        CreateZQOneProjectActivity.start(getActivity(), info,model.getSysAddressId(), model.getContacts(),model.getContactPhone());
                        return;
                    }

                    if (model.getProjectColumnList().getContinueFillingIn()) {
                        getTempData(model.getCreditorId(),model.getId());
                        return;
                    }
                    if ("0".equalsIgnoreCase(model.getProjectStatus())) {
                        //删除 V

                        noticeDialog
                                = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                            @Override
                            public void onClick( View view ) {
                                String  sendStatus = "";
                                if (view.getId() == R.id.btn_chancel_notice) {//暂存
                                    sendStatus = "1";
                                    noticeDialog.dismiss();
                                } else if (view.getId() == R.id.ll_close) {
                                    if (noticeDialog != null && noticeDialog.isShowing())
                                        noticeDialog.dismiss();
                                    return;
                                } else {//生成
                                    sendStatus = "2";
                                    noticeDialog.dismiss();
                                    DelData(model.getId(), position);
                                }

                                noticeDialog.dismiss();

                            }
                        }, 1, "提示", "确定删除项目", "取消", "确定");
                        noticeDialog.show();

                    } else if ("1".equalsIgnoreCase(model.getProjectStatus())) {

                    } else if ("2".equalsIgnoreCase(model.getProjectStatus())) {

                        if (!"".equalsIgnoreCase(model.getJoinId()) && "0".equalsIgnoreCase(model.getJoinType()) && "0".equalsIgnoreCase(model.getAcceptInvitation())) {
                            //拒绝
                            noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                                @Override
                                public void onClick( View view ) {
                                    String  sendStatus = "";
                                    if (view.getId() == R.id.btn_chancel_notice) {//暂存
                                        sendStatus = "1";
                                        noticeDialog.dismiss();
                                    } else if (view.getId() == R.id.ll_close) {
                                        if (noticeDialog != null && noticeDialog.isShowing())
                                            noticeDialog.dismiss();
                                        return;
                                    } else {//生成
                                        sendStatus = "2";
                                        noticeDialog.dismiss();
                                        accpectOrRefData(model.getId(), "2");
                                    }

                                    noticeDialog.dismiss();

                                }
                            }, 1, "提示", "确定拒绝邀请?\n拒绝邀请后将导致无法线上申报债权、参与表决等操作！", "取消", "确定");
                            noticeDialog.show();

                        } else {
                            // 管理 V
                            Intent intent = new Intent(getActivity(), ProDetailActivity.class);
                            intent.putExtra("info", new Gson().toJson(model));
                            getActivity().startActivity(intent);

                        }

                    } else if ("3".equalsIgnoreCase(model.getProjectStatus())) {
                    }

                } else if (v.getId() == R.id.bt_item_bt2) {

                    if ("0".equalsIgnoreCase(model.getProjectStatus())) {
                        // 管理 V
//                CreateProjectDetailActivity.start(getActivity(), model, 2);
                        EditProjectDetailActivity.start(getActivity(), model, 2);

                    } else if ("1".equalsIgnoreCase(model.getProjectStatus())) {

                    } else if ("2".equalsIgnoreCase(model.getProjectStatus())) {

                        if (!"".equalsIgnoreCase(model.getJoinId()) && "0".equalsIgnoreCase(model.getJoinType()) && "0".equalsIgnoreCase(model.getAcceptInvitation())) {
                            //接收邀请
//                    noticeDialog = new PublicNoticeDialog(getActivity(), onClickListener,
//                            1, "重要须知", "为了保障债权人的合法权益，加入前请再次确认您是相关债权人本人或法定代表人，或是其代理人，并将以本手机号码 188997688976 注册的账户代表相关债权人进行操作，如须变更号码线上操作，请点击变更操作用户，填写操作人的手机号。您也可联系管理人，由管理人协助操作用户加入。",
//                            "确认加入", "变更操作用户");
//                    noticeDialog.show();
                            ApplyProNoticeActivity.start(getActivity(),model.getId(),model.getCreditorId(),model.getSysAddressId(), model.getContacts(),model.getContactPhone());
                        }

                        //需判断是不是自己项目
                        if (model.getCreator().equalsIgnoreCase(BankruptcyApp.loginInfo.getId())) {
                            EditProjectDetailActivity.start(getActivity(), model, 2);
                        }
                    } else if ("3".equalsIgnoreCase(model.getProjectStatus())) {
                    }
                } else {
                    try {
                        if (!"0".equalsIgnoreCase(model.getProjectStatus())) {
                            if (model != null) {
                                Intent intent = new Intent(getActivity(), ProDetailActivity.class);
                                intent.putExtra("info", new Gson().toJson(model));
                                getActivity().startActivity(intent);
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        mDataRv.setAdapter(mAdapter);
    }



    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.ll_close:
                    noticeDialog.dismiss();
                    break;
                case R.id.btn_chancel_notice:
                    noticeDialog.dismiss();
                    noticelxDialog = new PublicLongNoticeDialog(getActivity(), onClickListener,
                            1, "", "",
                            "", "");
                    noticelxDialog.show();
                    break;
                case R.id.ll_close_lx:
                case R.id.btn_chancel_notice_lx:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    noticelxDialog.dismiss();

                    break;

                case R.id.btn_save_notice_lx:
                    Boolean flag = noticelxDialog.cb_agree.isChecked();
                    if (flag) {
//                        CreateZQOneProjectActivity.start(getActivity());
                    } else {
                        Toast.makeText(getActivity(), "请同意后再确认", Toast.LENGTH_LONG).show();
                    }
//                    noticelxDialog.dismiss();
                    break;

            }
        }
    };

    public void accpectOrRefData(String msgId, String type) {
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        if ("".equalsIgnoreCase(userToken)) {
            return;
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("projectId", msgId)
                .add("opType", type)
                .build();

        String url = Consts.WEBURL_ACCORREF;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);

                    if (object.optInt("code") == -10004 || (object.optInt("code") == -10003)) {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                LoginNoticeDialog.showPage(object.optString("msg"));
                            }

                        });
                        return;
                    }
                    if (object.optInt("code") == 0) {
//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

                                loadFirst();
                                Toast.makeText(getActivity(), "操作成功", Toast.LENGTH_SHORT).show();
                            }

                        });
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "操作失败:" + object.optString("msg"), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }


    public void DelData(String msgId, final int position) {
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        if ("".equalsIgnoreCase(userToken)) {
            return;
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("projectId", msgId)
                .build();

        String url = Consts.WEBURL_DELPRO;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                shapeLoadingDialog.dismiss();
                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                                mData.remove(position);
                                mAdapter.notifyDataSetChanged();
                                loadFirst();
                                Toast.makeText(getActivity(), "删除操作成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "请求失败:" + object.optString("msg"), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public void  getTempData
            (final String creditorId,final String proid)
    {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        Network.getAPIService()
                .fetchCreditorInfoTemp(userToken, creditorId,proid,"1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        try {
                            int code = json.get("code").getAsInt();

                            if (code != 0) {
                                ToastUtil.showShort("请求数据错误");
                                return;
                            }

                            JsonObject data = json.getAsJsonObject("data");
                            if(data == null ) {
                                ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                                info.setId(creditorId);
                                info.setBankruptcyProjectId(proid);
                                EditZQUserBaseInfoActivity.start(getActivity(), info, 1, 0);
                            }else {

                                ZQUserDetailBaseInfo info = new Gson().fromJson(json.getAsJsonObject("data"), ZQUserDetailBaseInfo.class);
                                info.setId(info.getCreditorId());
                                EditZQUserBaseInfoActivity.start(getActivity(), info, 1, 1);
                            }

//                            info.setBankruptcyProjectId(mProID);


                        }catch (Exception ex) {
                            ex.printStackTrace();
                            ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                            info.setId(creditorId);
                            info.setBankruptcyProjectId(proid);
                            EditZQUserBaseInfoActivity.start(getActivity(), info, 1, 0);

                        }
                    }

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        mDataRv.onFinishRequest(true, false);
                    }
                });
    }
    private long lastclick_getList;     // 防止网络重新请求
    public void getList() {

        if (System.currentTimeMillis() - lastclick_getList <= 1000) {
            return;
        }
        lastclick_getList = System.currentTimeMillis();
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        if("".equalsIgnoreCase(userToken))
        {
            mData.clear();
            mDataRv.onFinishRequest(false, true);
            return;
        }
        Network.getAPIService()
                .getMyProList(userToken, "", page, 20)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        try {
                            int code = json.get("code").getAsInt();

                            if  (code == -10004 || (code == -10003))
                            {

                                getActivity().runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        LoginNoticeDialog.showPage(json.get("msg").getAsString());
                                        mData.clear();
                                        mDataRv.onFinishRequest(false, true);
                                    }


                                });

                                return;
                            }

                            if (code != 0) {
                                if (page == 1)
                                    mData.clear();
                                mDataRv.onFinishRequest(true, false);
                                return;
                            }
                            JsonObject data = json.getAsJsonObject("data");
                            JsonArray arr = data.getAsJsonArray("list");
                            int totalCount = data.get("totalCount").getAsInt();
                            List<MyProInfo> list = MyProInfo.parse(arr);
                            if (page == 1)
                                mData.clear();
                            page++;
                            mData.addAll(list);
                            mDataRv.onFinishRequest(false, totalCount > mData.size());
                        }catch (Exception ex) {
                            ex.printStackTrace();
                            mData.clear();
                            mDataRv.onFinishRequest(false, true);
                        }
                    }

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        mDataRv.onFinishRequest(true, false);
                    }
                });
    }

    @Override
    public void loadFirst() {
        page = 1;
        getList();
    }

    @Override
    public void loadNext() {
        getList();
    }
}
